package pl.edu.mimuw.irs.rcp.persistence.descriptor;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.List;

import pl.edu.mimuw.irs.rcp.persistence.AbstractPersistence;

public class FileContainerPersistence extends AbstractPersistence<List<File>> {

	// *** Attributes

	// *** Methods

	@Override
	public List<File> loadFromStream(InputStream stream) throws Exception {
		List<File> files = new LinkedList<File>();
		List<String> paths = new LinkedList<String>();
		BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
		
		for (String line = reader.readLine(); line != null; line = reader.readLine()) {
			String path = line.trim();
			if (path.equals("")) continue;
			if (paths.contains(path)) continue;
			paths.add(path);
			files.add(new File(path));
		}
		return files;
	}

	@Override
	public void writeToStream(List<File> files, OutputStream stream)
			throws Exception {
		
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream));
		
		for (File file : files) {
			writer.write(file.getPath()); 
			writer.newLine();
		}
		writer.close();
	}


}
